using System;
using System.Collections.Generic;
using System.Text;

namespace GoogleNet
{
    /// <summary>
    /// Represents a single moment in time. This is a simple element and contains no children. 
    /// Its value is a dateTime, specified in XML time (see XML Schema Part 2: Datatypes Second Edition). 
    /// The precision of the TimeStamp is dictated by the dateTime value in the when element.
    /// </summary>
    public class KmlTimeStamp : KmlTimePrimitive
    {
        private string tagName = "TimeStamp";

        #region When
        private DateTime when;

        /// <summary>
        /// Specifies a single moment in time. The value is a dateTime.
        /// </summary>
        /// <value>The when.</value>
        public DateTime When
        {
            get { return when; }
            set { when = value; }
        } 
        #endregion


        #region IKmlElement Members

        /// <summary>
        /// Name of the KML tag for this specific element.
        /// </summary>
        /// <value></value>
        /// <returns></returns>
        public override string TagName
        {
            get { return tagName; }
        }

        #endregion

        #region IKmlGenerator Members

        /// <summary>
        /// Generates the KML for this element including its child elements.
        /// </summary>
        /// <param name="writer">The XML writer that will be used to generate the KML.</param>
        public override void GenerateKml(System.Xml.XmlTextWriter writer)
        {
            writer.WriteStartElement(tagName);
            base.GenerateKml(writer);

            if (when != null)
                writer.WriteElementString("when", convertDateToKml(when));

            writer.WriteEndElement();
        }

        #endregion

        /// <summary>
        /// Converts a date to KML date type.
        /// </summary>
        /// <param name="date">The date.</param>
        /// <returns></returns>
        private string convertDateToKml(DateTime date)
        {
            date = date.ToUniversalTime();

            StringBuilder dateBuilder = new StringBuilder();
            dateBuilder.Append(date.Year.ToString());
            dateBuilder.Append("-");
            dateBuilder.Append(date.Month.ToString());
            dateBuilder.Append("-");
            dateBuilder.Append(date.Day.ToString());
            dateBuilder.Append("T");
            dateBuilder.Append(date.Hour.ToString());
            dateBuilder.Append(":");
            dateBuilder.Append(date.Minute.ToString());
            dateBuilder.Append(":");
            dateBuilder.Append(date.Second.ToString());
            dateBuilder.Append("Z");

            return dateBuilder.ToString();
        }
    }
}
